package conn

import (
	"chatting/dao"
	"chatting/model"
	"fmt"
	"github.com/gogf/gf/v2/net/gtcp"
	"log"
)

func (server *Server) RegisterHandle(conn *gtcp.Conn, msg *model.RegisterMessage) {
	username := msg.Username
	password := msg.Password
	email := msg.Email
	ifU := dao.GetUserFromName(msg.Username)
	fmt.Println("ifU", ifU)
	if ifU.ID != 0 {
		HandleErr(conn, "用户名已被占用")
		return
	}
	user, err := dao.AddUser(&model.User{Username: username, Password: password, Email: email})
	if err != nil {
		HandleErr(conn, err)
		return
	}
	HandleSuccess(conn, user)
}

func (server *Server) LoginHandle(conn *gtcp.Conn, msg *model.LoginMessage) {
	username := msg.Username
	password := msg.Password
	user := dao.GetUserFromName(username)
	if user.Username == "" || user.Password != password {
		HandleErr(conn, "用户名或密码错误")
		return
	}
	//fmt.Println("userInfo", user)
	server.OnlineUsers[username] = conn
	userInfo := new(model.ResUserInfoMessage)
	userInfo.UserInfo = user
	conn.SendPkg(userInfo.Package())
}

func (server *Server) ChatHandle(conn *gtcp.Conn, msg *model.ChatMessage) {
	if toConn, ok := server.OnlineUsers[msg.ToUser]; !ok { //好友不在线的情况
		m := new(model.ResChatMessage)
		m.MessageFrom = msg.ToUser
		m.Data = "好友不在线"
		conn.SendPkg(m.Package())
		return
	} else { //好友在线的情况
		//给我和好友同时发这个消息
		conn.SendPkg(msg.ToResChat())
		toConn.SendPkg(msg.ToResChat())
		fmt.Println("服务器发送聊天消息", msg)
	}
}

func (server *Server) PingHandle(conn *gtcp.Conn) {
	bytes := model.NewTrueResWithPong().Package()
	conn.SendPkg(bytes)
}

func HandleErr(conn *gtcp.Conn, err interface{}) {
	res := model.NewFalseRes(err)
	bytes := res.Package()
	err = conn.SendPkg(bytes)
	if err != nil {
		log.Println(err)
	}
}

func HandleSuccess(conn *gtcp.Conn, in interface{}) {
	res := model.NewTrueRes(in)
	bytes := res.Package()
	in = conn.SendPkg(bytes)
	if in != nil {
		log.Println(in)
	}
}
